package com.gu.common.utils.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.format.CellFormat;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Color;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.List;

/**
 * @author Mr.Gu
 * @date 2020/10/13 10:08
 * @function : 自定义操作Excel工具类
 **/
public class ExcelUtil {
    private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 修改Excel中指定的单元格
     */
    public static void updateCell() {
        Workbook wb =null;

        String filePath = "E:\\经济指标的影响模型.xlsx";

        //创建Workbook对象
        wb = createWorkbook(filePath);

        //如果文件不为空
        if(wb != null){
            Sheet sheetAt = wb.getSheetAt(0);
            Row row = sheetAt.getRow(7);
            Cell cell = row.getCell(6);
            cell.setCellValue(0.2);

            //修改后让表格中所有公式重新计算
            wb.getCreationHelper().createFormulaEvaluator().evaluateAll();

            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(new File(filePath));
                wb.write(fileOutputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (wb != null) {
                    try {
                        wb.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 读取excel中的数据
     * @param file
     * @return
     */
    public static List<Map<Object,Object>> readExcelData(File file) {

        //用来存放表中数据
        List<Map<Object,Object>> mapList = null;
        Workbook wb =null;

        String filePath = "E:\\电价变动对宏观经济指标的影响模型-简化-右下.xlsx";

        //创建Workbook对象
        wb = createWorkbook(filePath);

        //如果文件不为空
        if(wb != null){
            mapList = new ArrayList<>();
            //获取第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            Row row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();

            //循环行
            Object cellData = null;
            Map<Object,Object> data = null;
            for (int i = 0; i< rownum; i++) {
                //从第一行开始，获取每一行的数据
                row = sheet.getRow(i);
                if(row !=null){
                    data = new LinkedHashMap<>();
                    //循环列，拿到这一行中每一列的内容
                    for (int j=0;j<colnum;j++){
                        //获取对应行的列的内容
                        cellData = getCellFormatValue(row.getCell(j));
                        //将这一列的名称作为key，内容作为value，放到map中
                        data.put((i+1)+"行"+(j+1)+"列",cellData);
                    }
                    mapList.add(data);
                }else{
                    break;
                }
            }
        }
        return mapList;
    }

    public static void exportExcel() {
        Workbook wb = null;
        OutputStream os = null;
        ByteArrayOutputStream outputStream = null;

        try {
            //创建工作簿
            wb = createWorkbook(".xlsx");
            //给Excel设置水印
            painWaterMark(wb,"I Love You");

            outputStream = new ByteArrayOutputStream();
            wb.write(outputStream);

            byte[] bytes = outputStream.toByteArray();
            File file = new File("E:\\test_excel"+System.currentTimeMillis()+".xlsx");

            os = new FileOutputStream(file);
            os.write(bytes);
            outputStream.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据文件格式创建Workbook
     * @param filePath
     * @return
     */
    private static Workbook createWorkbook(String filePath) {
        Workbook wb = null;
        String extString = filePath.substring(filePath.lastIndexOf("."));//文件后缀名
        try {
            InputStream is = new FileInputStream(filePath);
            //如果文件后缀名为xls
            if (".xls".equals(extString)) {
                wb = new HSSFWorkbook(is);
            }//如果文件后缀名为xlsx
            else if (".xlsx".equals(extString)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = null;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * 读取指定单元格中的内容
     * @param cell
     * @return
     */
    private static Object getCellFormatValue(Cell cell){
        Object cellValue = null;

        if(cell!=null){

            if (0 == cell.getCellType()) {
                //判断cell是否为日期格式
                if(DateUtil.isCellDateFormatted(cell)){
                    cellValue = cell.getDateCellValue();
                }else {
                    //处理整型
                    cellValue = cell.getNumericCellValue();
                    //百分比数值
                    String showValue= CellFormat.getInstance(cell.getCellStyle().getDataFormatString()).apply(cell).text;
                    if (showValue.indexOf("%") != -1) {
                        cellValue = showValue;
                    }
                }
            }else if(1 == cell.getCellType()){
                //字符串类型
                cellValue = cell.getRichStringCellValue().getString();
            }else  if(2 == cell.getCellType()) {
                //表达式
                cellValue = CellFormat.getInstance(cell.getCellStyle().getDataFormatString()).apply(cell).text;
            }else if (4 == cell.getCellType()) {
                //boolean类型
                cellValue = cell.getBooleanCellValue();
            }
        }
        return cellValue;
    }

    public static void painWaterMark(Workbook wb,String content) {
        String imgFileName = "waterMark_photo_"+content+".png";
        //创建图片
        createWaterMark(content,imgFileName);

        //创建工作簿sheet
        Sheet sheet1 = wb.createSheet("Sheet1");
        //设置工作簿的保护模式，使用UUID创建随机值作为密码
        sheet1.protectSheet(UUID.randomUUID().toString());

        //将图片写入到excel中
        try {
            putWaterRemarkToExcel(wb, sheet1, imgFileName, 0, 0, 5, 5,
                    5, 10, 2, 2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建水印图片
     * @param content
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String createWaterMark(String content, String fileName) {
        Integer width = 300;
        Integer height = 150;
        // 获取bufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        String fontType = "宋体";
        Integer fontStyle = java.awt.Font.PLAIN;
        Integer fontSize = 50;
        java.awt.Font font = new java.awt.Font(fontType, fontStyle, fontSize);
        // 获取Graphics2d对象
        Graphics2D g2d = image.createGraphics();
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        g2d.setColor(new Color(0, 0, 0, 80)); //设置字体颜色和透明度
        // 设置字体
        g2d.setStroke(new BasicStroke(1));
        // 设置字体类型  加粗 大小
        g2d.setFont(font);
        //设置倾斜度
        g2d.rotate(Math.toRadians(-10), (double) image.getWidth() / 2, (double) image.getHeight() / 2);
        FontRenderContext context = g2d.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(content, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        // 写入水印文字原定高度过小，所以累计写水印，增加高度
        g2d.drawString(content, (int) x, (int) baseY);
        // 设置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 释放对象
        g2d.dispose();
        String targetImagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()+fileName;
        try {
            ImageIO.write(image, "png", new File(targetImagePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return targetImagePath;
    }

    /**
     * 为Excel打上水印工具函数 请自行确保参数值，以保证水印图片之间不会覆盖。 在计算水印的位置的时候，并没有考虑到单元格合并的情况，请注意
     * @param wb Excel Workbook
     * @param sheet 需要打水印的Excel
     * @param waterRemarkPath 水印地址，classPath，目前只支持png格式的图片，
     *                        因为非png格式的图片打到Excel上后可能会有图片变红的问题，且不容易做出透明效果。
     *                        同时请注意传入的地址格式，应该为类似："\\excelTemplate\\test.png"
     * @param startXCol 水印起始列
     * @param startYRow 水印起始行
     * @param betweenXCol 水印横向之间间隔多少列
     * @param betweenYRow 水印纵向之间间隔多少行
     * @param XCount 横向共有水印多少个
     * @param YCount 纵向共有水印多少个
     * @param waterRemarkWidth 水印图片宽度为多少列
     * @param waterRemarkHeight 水印图片高度为多少行
     * @throws IOException
     */
    public static void putWaterRemarkToExcel(Workbook wb, Sheet sheet, String waterRemarkPath, int startXCol,
                                             int startYRow, int betweenXCol, int betweenYRow, int XCount, int YCount, int waterRemarkWidth,
                                             int waterRemarkHeight) throws IOException {

        // 校验传入的水印图片格式
        if (!waterRemarkPath.endsWith("png") && !waterRemarkPath.endsWith("PNG")) {
            throw new RuntimeException("向Excel上面打印水印，目前支持png格式的图片。");
        }
        // 加载图片
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        //InputStream imageIn = new FileInputStream(waterRemarkPath);
        InputStream imageIn = Thread.currentThread().getContextClassLoader().getResourceAsStream(waterRemarkPath);
        if (null == imageIn || imageIn.available() < 1) {
            throw new RuntimeException("向Excel上面打印水印，读取水印图片失败(1)。");
        }
        BufferedImage bufferImg = ImageIO.read(imageIn);
        if (null == bufferImg) {
            throw new RuntimeException("向Excel上面打印水印，读取水印图片失败(2)。");
        }
        ImageIO.write(bufferImg, "png", byteArrayOut);

        // 开始打水印
        Drawing drawing = sheet.createDrawingPatriarch();

        // 按照共需打印多少行水印进行循环
        for (int yCount = 0; yCount < YCount; yCount++) {
            // 按照每行需要打印多少个水印进行循环
            for (int xCount = 0; xCount < XCount; xCount++) {
                // 创建水印图片位置
                int xIndexInteger = startXCol + (xCount * waterRemarkWidth) + (xCount * betweenXCol);
                int yIndexInteger = startYRow + (yCount * waterRemarkHeight) + (yCount * betweenYRow);

                /** 参数定义： 第一个参数是（x轴的开始节点）； 第二个参数是（是y轴的开始节点）； 第三个参数是（是x轴的结束节点）；
                 * 第四个参数是（是y轴的结束节点）； 第五个参数是（是从Excel的第几列开始插入图片，从0开始计数）；
                 * 第六个参数是（是从excel的第几行开始插入图片，从0开始计数）； 第七个参数是（图片宽度，共多少列）；
                 * 第8个参数是（图片高度，共多少行）；*/

                ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, xIndexInteger,
                        yIndexInteger, xIndexInteger + waterRemarkWidth, yIndexInteger + waterRemarkHeight);

                Picture pic = drawing.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG));
                pic.resize();
            }
        }
    }
}
